import {
	ethers
} from 'ethers'
import { checkWalletSign } from '../request/login'
import Web3 from 'web3';
import i18n from '@/lang';

// import store from '../store'

const INFO = {

	idoabi: [
		"function pay(uint256 amount) external",
	],
	tokenabi: [
		'function transfer( address recipient, uint256 amount ) external returns (bool)',
		'function allowance(address owner, address spender) external view returns (uint256)',
		'function approve(address spender, uint256 amount) external returns (bool)',
		'function balanceOf(address account) external view returns (uint256)',
		'function symbol() external view returns (string memory)',
		'function decimals() external pure returns (uint8)',
	],
	withdrawabi: [
		'function withdraw(tuple(address token, uint256 amount, address recipient, uint256 deadline, uint256 nonce), uint8 v, bytes32 r, bytes32 s) external',
	],
	swapABI: [
		"function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts)",
	]
}
const contract = { // 支付地址 天sheng
	"USDT": "0xbDe9e69a793DA17f3d42aD4d6ce4028A0c437C77",
	"FST": "0xF3FfD745DCD9f69419D410779f23F7AdF21f7d12"
}
// const contract = { // 支付地址
// 	"USDT": "0x9732C3C2153902C33b65a3ca8386A434abBe9063",
// 	"FST": "0x504109c8B6DBd2daD74Fb829614A6F090A8B57EE"
// }

const routerAddr = { // 币种地址 tiansheng
	"USDT":"0x81243a879538Afc45C6259130F00F307F16e2550",
	"FST":"0x87A4a5D5d1629aA6f3F46A735E9379f038127D92",
}
// const routerAddr = { // 币种地址
// 	"USDT":"0x55d398326f99059fF775485246999027B3197955",
// 	"FST":"0x77bc1d08f4d457c93bd65d4d716c0e2cd843e38e",
// }

// 链信息
const chainObj = {

}

let useAccount = null

const connectWallet = async (type = '') => {
	try {
		// if (!useAccount) {
		// 	await connectMetamask()
		// 	return useAccount;
		// } else {
		// 	return useAccount;
		// }
		if (!useAccount) {
			await connectMetamask(type)
		}
		const web3 = new Web3(window.ethereum);
		let message = "I have read and accept the terms and conditions."
		if(type != ''){
			return {useAccount:useAccount};
		}
		let signature = await web3.eth.personal.sign(message, useAccount)
		const judgeCondition = await checkWalletSign({sign:signature , address:useAccount})
		// console.log(judgeCondition, "signature")
		if (judgeCondition.code == 1) {
			return {useAccount:useAccount , sign:signature};
		}else{
			return false
		}
	} catch (connectError) {
		return {
			err: connectError
		};
	}

}

const checkWallet = () => {
	if (window.bitkeep && window.bitkeep.ethereum) {
		return true;
	} else if (window.ethereum) {
		return true;
	} else {
		return false;
	}
}

const connectMetamask = async (type) => {
	let provider;
	if (window.bitkeep && window.bitkeep.ethereum) {
		provider = new ethers.providers.Web3Provider(window.bitkeep.ethereum);
	} else if (window.ethereum) {
		provider = new ethers.providers.Web3Provider(window.ethereum);
	} else {
		alert(i18n.t('请安装MetaMask钱包或其他以太坊兼容钱包'));
		return;
	}
	try {
		await provider.send("eth_requestAccounts", []);
		// const addressArray = await provider.send("eth_requestAccounts", []);
		const signer = provider.getSigner();
		useAccount = await signer.getAddress()
		provider.provider.on('accountsChanged', (accounts) => {
			if (accounts.length > 0) {
				useAccount = accounts[0];
			} else {
				useAccount = null; // 如果没有账户，重置 useAccount
			}
		});
	} catch (error) {
		console.error('钱包连接失败:', error);
	}
}
// const connectMetamask = async () => {
// 	if (!window.ethereum) return alert('please connect wallet');
// 	let addressArray;
// 	try {	
// 			addressArray = await window.ethereum.request({
// 					method: "eth_requestAccounts",
// 			});
// 			console.log(4)
// 			console.log(addressArray, "addressArray")
// 			if (addressArray.length !== 0) {
// 					const user_addr = ethers.utils.getAddress(addressArray[0]);
// 					console.log(user_addr , 1)
// 					useAccount = user_addr;

// 					return user_addr
// 			}
// 	} catch (connectError) {
// 			return {
// 					err: connectError
// 			};
// 	}

// }
// 获取币价
const getAmountsOut = async (tokenA, tokenB) => {
	if (!window.ethereum) return {
		error: true,
		msg: 'please connect wallet'
	}
	const provider = new ethers.providers.Web3Provider(window.ethereum)
	const signer = provider.getSigner()
	const tA = new ethers.Contract(tokenA, INFO.tokenabi, provider)
	const dA = await tA.decimals()
	const router = new ethers.Contract(INFO.routerAddr, INFO.swapABI, signer)
	const iv = ethers.utils.parseUnits('1', dA)

	const [, amount1] = await router.getAmountsOut(iv, [tokenA, tokenB])

	const token = new ethers.Contract(tokenB, INFO.tokenabi, provider)

	const decimals = await token.decimals()

	return ethers.utils.formatUnits(amount1, decimals)
}
// 质押
const deposit = async (amount,currency) => {
	const depositAddress = contract[currency];
	const usdtAddr = routerAddr[currency]
	console.log(amount , usdtAddr, depositAddress , window.ethereum ,123)
	if (!window.ethereum) return {
		error: true,
		msg: 'please connect wallet'
	}

	if (!useAccount) await connectWallet()
	let provider;

	if (window.bitkeep && window.bitkeep.ethereum) {
		provider = new ethers.providers.Web3Provider(window.bitkeep.ethereum);
	} else if (window.ethereum) {
		provider = new ethers.providers.Web3Provider(window.ethereum);
	} else {
		return;
	}

	const signer = provider.getSigner()
	const token = new ethers.Contract(usdtAddr, INFO.tokenabi, signer)
	const allowance = await token.allowance(useAccount, depositAddress)
	if (allowance.lt(ethers.utils.parseUnits(amount, 18))) {
		// console.log(7)
		const tx = await token.approve(depositAddress, ethers.constants.MaxUint256)
		// console.log(8)
		await tx.wait()
		// console.log(9)
	}
	// console.log(10)
	const ido = new ethers.Contract(depositAddress, INFO.idoabi, signer)
	// console.log(11)
	const tx = await ido.pay(ethers.utils.parseUnits(amount, 18))
	// console.log(12)
	return tx
}

const checkAllowance = async (useAccount) => {
	const depositAddress = store.state.depositAddress;
	const usdtAddr = store.state.usdtAddr
	if (!window.ethereum) return {
		error: true,
		msg: 'please connect wallet'
	}
	if (!useAccount) await connectWallet()
	let provider;
	if (window.bitkeep && window.bitkeep.ethereum) {
		provider = new ethers.providers.Web3Provider(window.bitkeep.ethereum);
	} else if (window.ethereum) {
		provider = new ethers.providers.Web3Provider(window.ethereum);
	} else {
		return;
	}
	const signer = provider.getSigner()
	const token = new ethers.Contract(usdtAddr, INFO.tokenabi, signer)
	const allowance = await token.allowance(useAccount, depositAddress)

	const amountUint256 = ethers.constants.MaxUint256;
	if (allowance.lt(amountUint256)) {
		const tx = await token.approve(depositAddress, amountUint256)
		await tx.wait()
	}
	return 200

}
let withdrawToken = async (tokenADDR, amount, recipient, deadline, nonce, v, r, s) => {
	const withdrawAddr = store.state.withdrawAddr;
	if (!window.ethereum) return {
		error: true,
		msg: 'please connect wallet'
	}
	if (!useAccount) await connectWallet()
	let provider;
	if (window.bitkeep && window.bitkeep.ethereum) {
		provider = new ethers.providers.Web3Provider(window.bitkeep.ethereum);
	} else if (window.ethereum) {
		provider = new ethers.providers.Web3Provider(window.ethereum);
	} else {
		return;
	}
	let signer = provider.getSigner()
	let token = new ethers.Contract(withdrawAddr, INFO.withdrawabi, signer)
	let tx = await token.withdraw([tokenADDR, amount, recipient, deadline, nonce], v, r, s)
	return tx
}
// const getChain = async () => {
// 	let Id = '0xf423f'
// 	if (window.ethereum) {
// 		try {
// 			const chainId = await window.ethereum.request({
// 				method: "eth_chainId"
// 			});
// 			console.log(chainId,chainId === Id, "chainId")
// 			if (chainId === Id) return 'bsc';
// 		} catch (error) {

// 		}
// 	} else if (window.bitkeep && window.bitkeep.ethereum) {
// 		const Provider = window.bitkeep.ethereum;
// 		const isBitKeepValue = Provider.isBitKeep;
// 		if (isBitKeepValue) {
// 			try {
// 				const accounts = await Provider.request({
// 					method: 'eth_requestAccounts'
// 				});
// 				if (accounts.length === 0) {
// 					console.warn('No accounts found. User may not be connected.');
// 					return 'unknown1';
// 				}
// 				const chainId = await Provider.request({
// 					method: 'eth_chainId'
// 				});
// 				// console.log(chainId,"chainId")
// 				if (chainId === Id) return 'bsc';
// 			} catch (error) {
// 				console.error('Error fetching accounts or chain ID from BitKeep:', error);
// 			}
// 		}
// 	}
// 	// console.log(chainId,"chainId")
// 	return 'unknown';
// };
const getChain = async () => {
	const BSC_CHAIN_ID = '0xf423f'; // 天晟链id
	// const BSC_CHAIN_ID = '0x38'; // bi an链
	let provider;
	if (window.tokenpocket && window.tokenpocket.ethereum) {
			provider = window.tokenpocket.ethereum;
			try {
					const chainId = await provider.request({
							method: 'eth_chainId'
					});
					if (chainId === BSC_CHAIN_ID) return 'bsc';
					// 方法3：如果是 TokenPocket 且返回 0x1，尝试特殊处理
					if (chainId === '0x1' && window.tokenpocket) {
							// 尝试获取账户来刷新状态
							await provider.request({
									method: 'eth_requestAccounts'
							});
							// 再次尝试获取链 ID
							const refreshedChainId = await provider.request({
									method: 'eth_chainId'
							});
							if (refreshedChainId === BSC_CHAIN_ID) return 'bsc'
					}
			} catch (error) {
					console.error('Error detecting chain:', error);
			}
			return 'unknown';
	} else if (window.ethereum) {
			provider = window.ethereum;
			const chainId = await window.ethereum.request({
					method: "eth_chainId"
			});
			if (chainId === BSC_CHAIN_ID) return 'bsc';
			if (chainId === '0x1') {
					await provider.request({
							method: 'eth_requestAccounts'
					});
					// 再次尝试获取链 ID
					const refreshedChainId = await provider.request({
							method: 'eth_chainId'
					});
					if (refreshedChainId === BSC_CHAIN_ID) return 'bsc'
			}
	}
	if (!provider) return 'unknown';

};

//获取BNB(公链币)余额
const getBNBalance = async (useAccount) => {
	let provider;
	if (window.bitkeep && window.bitkeep.ethereum) {
		provider = new ethers.providers.Web3Provider(window.bitkeep.ethereum);
	} else if (window.ethereum) {
		provider = new ethers.providers.Web3Provider(window.ethereum);
	} else {
		return;
	}
	const balance = await provider.getBalance(useAccount);
	return ethers.utils.formatUnits(balance)
}
const USDTBalance = async (useAccount) => {
	if (!window.ethereum) return {
		error: true,
		msg: 'please connect wallet'
	}
	if (!useAccount) return {
		error: true,
		msg: 'please connect wallet'
	}
	let provider;
	if (window.bitkeep && window.bitkeep.ethereum) {
		provider = new ethers.providers.Web3Provider(window.bitkeep.ethereum);
	} else if (window.ethereum) {
		provider = new ethers.providers.Web3Provider(window.ethereum);
	} else {
		return;
	}
	const usdtAddr = store.state.usdtAddr
	const token = new ethers.Contract(usdtAddr, INFO.tokenabi, provider)
	const bal = await token.balanceOf(useAccount)
	const decimals = await token.decimals()
	return ethers.utils.formatUnits(bal, decimals)
}

// 不走合约转账-代币
const noZhuan = async (daibiAddress, toAddress, toNum) => {
	if (!window.ethereum) {
		console.error("No Ethereum wallet found. Please install MetaMask.");
		return;
	}
	// console.log(daibiAddress,toAddress,toNum,"1")
	try {
		// 1. 请求连接用户的钱包
		await window.ethereum.request({
			method: "eth_requestAccounts"
		});

		let num = String(toNum) // 转账的代币数量
		// console.log(2)
		// 2. 创建一个 ethers.js 的 provider
		const provider = new ethers.providers.Web3Provider(window.ethereum)
		// console.log(3)
		// 3. 获取签名器
		const signer = await provider.getSigner();
		// console.log(4)
		// 4. ERC20 合约地址和 ABI
		const tokenAddress = daibiAddress; // 替换为代币合约地址
		const tokenAbi = INFO.tokenabi
		// console.log(5)
		// 5. 创建代币合约实例
		const tokenContract = new ethers.Contract(tokenAddress, tokenAbi, signer);
		// console.log(6)
		// 6. 设置目标地址和转账数量（转换为代币的最小单位）
		const recipient = toAddress; // 接收方地址
		// console.log(7)
		const amount = ethers.utils.parseUnits(num, 18); // 转账 10 个代币，假设代币有 18 位小数
		// console.log(8)
		// 7. 发起代币转账
		const tx = await tokenContract.transfer(recipient, amount);
		// console.log(9)
		// console.log("Transaction sent. Hash:", tx.hash);

		// 8. 等待交易确认
		const receipt = await tx.wait();
		// console.log("Transaction confirmed. Receipt:", receipt);
		// console.log(10)
		return receipt
	} catch (error) {
		console.error("Error during token transfer:", error);
		return error
	}
}



export {
	checkWallet,
	connectWallet,
	// getBNBalance,
	deposit,
	getChain,
	// withdrawToken,
	// USDTBalance,
	// checkAllowance,
	// INFO,
	// getAmountsOut,
	// noZhuan


}